package com.zjpavt.taiyuan.controller.base;


import com.zjpavt.taiyuan.service.TaiyuanCustomException;
import com.zjpavt.taiyuan.utils.LoggerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * Controller层全局异常处理类
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * 自定义异常处理
	 *
	 */
	@ExceptionHandler({TaiyuanCustomException.class})
	@ResponseBody
	public String handleCustomException(TaiyuanCustomException customException, HttpServletResponse response){
		//response.setStatus(ResponseCode.REPONSE_STATUS_CUSTOM_EXCEPTION);
		//response.addHeader("ExceptionMSG",customException.getMessage());
		logger.debug(customException.getMessage());
		return new ResponseResult(ResponseCode.ERROR,customException.getMessage(),null).toString();
	}

	/**
	 * 非自定义异常处理
	 *
	 * @param exception
	 * @return
	 */
	@ExceptionHandler({Exception.class})
	@ResponseBody
	public String handleException(Exception exception, HttpServletResponse response) {
		//response.setStatus(ResponseCode.REPONSE_STATUS_UNKNOWN_EXCEPTION);
		//response.addHeader("ExceptionMSG","未知错误,请提供错误时间，联系历史数据系统管理员");
		logger.error(LoggerUtil.convertException2String(exception));
		return new ResponseResult(ResponseCode.ERROR,"未知错误,请提供错误时间，联系灯光秀系统管理员",null).toString();
    }

	/**
	 * 处理JSR-303传入参数校验异常
	 * @param e
	 * @return
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public String methodArgumentNotValidException(MethodArgumentNotValidException e) {
		logger.error(LoggerUtil.convertException2String(e));
		return new ResponseResult(ResponseCode.ERROR, e.getLocalizedMessage(), null).toString();
	}
}
